package com.thinkSoft.Location.Activities;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.thinkSoft.Location.R;
import com.thinkSoft.Location.Helpers.Debugger;
import com.thinkSoft.Location.Lib.DataFunc;
import com.thinkSoft.Location.Services.Background;

public class UIMap extends MapActivity implements LocationListener {
	MapView mapView = null;
	MapController myMapController = null;
	LocationManager lm;
	Boolean gpsPrompt = false;
	private Debugger debug = new Debugger(this);
	MyLocationOverlay myLocationOverlay = null;
	Boolean movedTarget = false;
	DataFunc data = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		checkLogin();    
		data = new DataFunc();
		setContentView(R.layout.activity_uimap);
		mapView = (MapView) findViewById(R.id.mapView);
		myMapController = mapView.getController();
		mapView.setBuiltInZoomControls(true);
		mapView.displayZoomControls(true);
		mapView.setSatellite(true);
		myLocationOverlay = new MyLocationOverlay(this, mapView);
		mapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass(); // if you want to display a compass also
		myLocationOverlay.enableMyLocation();
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		String provider = lm.getBestProvider(criteria, true);
		if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
		}
		else{
			if (!gpsPrompt){
				gpsPrompt = true;
				buildAlertMessageNoGps();
			}
			lm.requestLocationUpdates(provider, 0, 0, this);
			debug.postLog(Log.DEBUG, "MapView", "Choosing - " + provider);
			
		}
		Intent intent = new Intent();
		intent.setAction(Background.TrackAction);
		sendBroadcast(intent);
	}

	private void checkLogin() {
		DataFunc userDb = new DataFunc();
		if(!userDb.isUserLoggedIn(getApplicationContext())){
			// user is not logged in show login screen
			Intent login = new Intent(getApplicationContext(), UILogin.class);
			login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(login);
			// Closing dashboard screen
			finish();            
		}
	}
	private void buildAlertMessageNoGps() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Your GPS appears to be disabled, to get the best location fix it should be enabled.\n\nWould you like to enable it?")
		.setCancelable(false)
		.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(final DialogInterface dialog, final int id) {
				startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
			}
		})
		.setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(final DialogInterface dialog, final int id) {
				dialog.cancel();
			}
		});
		final AlertDialog alert = builder.create();
		alert.show();
	}
	@Override
	protected void onDestroy() {
		lm.removeUpdates(this);
		myLocationOverlay.disableMyLocation();
		myLocationOverlay.disableCompass();
		super.onDestroy();
	}
	@Override
	protected void onPause() {
		lm.removeUpdates(this);
		myLocationOverlay.disableMyLocation();
		myLocationOverlay.disableCompass();
		// TODO Auto-generated method stub
		super.onPause();
	}
	@Override
	protected void onResume() {
		if (myLocationOverlay != null){
			myLocationOverlay.enableCompass();
			myLocationOverlay.enableMyLocation();
		}
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		String provider = lm.getBestProvider(criteria, true);
		lm.requestLocationUpdates(provider, 0, 0, this);
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_uimap, menu);
		return true;
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// app icon in action bar clicked; go home
			Intent intent = new Intent(this, UIDashboard.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		case R.id.smode:
			if (mapView.isSatellite()){
				mapView.setSatellite(false);
				Toast.makeText(this, "Map mode.", Toast.LENGTH_SHORT).show();
			}
			else{
				mapView.setSatellite(true);
				Toast.makeText(this, "Satellite mode.", Toast.LENGTH_SHORT).show();
			}
			return true;
		case R.id.myloc:
			Criteria crit = new Criteria();
			crit.setAccuracy(Criteria.ACCURACY_FINE);
			String provider = lm.getBestProvider(crit, true);
			Location loc = lm.getLastKnownLocation(provider);
			myMapController.animateTo(getGeo(loc));
			myMapController.setZoom(16);
			return true;
		case R.id.logout:
			DataFunc userFunctions = new DataFunc();
			userFunctions.logoutUser(getApplicationContext());
			Intent login = new Intent(getApplicationContext(), UILogin.class);
			login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(login);
			lm.removeUpdates(this);
			finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		if (!movedTarget){
			myMapController.animateTo(getGeo(location));
			movedTarget = true;
			myMapController.setZoom(16);			
		}		
	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}
	public GeoPoint getGeo(Location loc){
		GeoPoint point = new GeoPoint(
				(int) (loc.getLatitude() * 1E6), 
				(int) (loc.getLongitude() * 1E6));
		return point;

	}



}
